package com.as3extensions.helpers {
  
  public class EnumerableHelper {
    
    public static function map( array : Array, iterator : Function ) : Array {
      return EnumerableHelper.collect( array, iterator );
    }   
    
    public static function collect( array : Array, iterator : Function ) : Array {
      var results : Array = [];
      
      for ( var index : int = 0; index < array.length; index++ )
        results.push( iterator(array[index], index) );

      return results;
    }
    
    public static function detect( array : Array, iterator : Function ) : Array {
      var result : * = null;
      
      for ( var index : int = 0; index < array.length; index++ ) {
        var value : * = array[index];
        
        if ( iterator( value, index ) ) {
          result = value;
          break;
        }
      }
      return result;
    }
    
    public static function findAll( array : Array, iterator : Function ) : Array {
      var results : Array = new Array();
      
      for ( var index : int = 0; index < array.length; index++ ) {
        var value : * = array[index];
        
        if ( iterator( value, index ) )
          results.push(value);
      }
      return results;
    }
    
    public static function inject( array : Array, memo : *, iterator : Function ) : * {
      for ( var index : int = 0; index < array.length; index++ )
        memo = iterator( memo, array[index], index );
      
      return memo;
    }
    
    public static function invoke( array : Array, method : String, ...args ) : Array {
      return EnumerableHelper.map( array, function( value : *, index : int ) : * {
        return value[method].apply(value, args);
      });
    }
  }
}